<template>
  <div class="ChildPage TablePage" v-loading="loading">
    <vb-page ref="page" @onTableSelection="doSelect">
<!--      <template #headerSearch-append="scope">-->
<!--        <el-checkbox v-model="scope.searchForm.isNotRfid" style="margin: 0 10px" size="mini" label="是否包含未关联"></el-checkbox>-->
<!--      </template>-->
      <template #headerBtn="scope">
        <el-button size="small" icon="el-icon-upload2" type="warning" @click="$refs.upload_dialog.show()">批量上传</el-button>
        <el-button size="small" icon="el-icon-plus" type="primary" @click="gotoDetail()">新增</el-button>
        <el-button size="small" type="success"  icon="el-icon-share" @click="toExport(this.selection)" :disabled="isExport()">导出</el-button>
      </template>
      <template #table-status="scope">
        <el-tag :type="scope.row.status === 'save'? 'info': 'success'">{{ scope.row.status === 'save'? '保存': '审核' }}</el-tag>
      </template>
      <template #table-isPrint="scope">
        <el-tag :type="scope.row.isPrint === 'seal'? 'success': 'info'" >{{ scope.row.isPrint === 'seal'? '已打印': '未打印' }}</el-tag>
      </template>
      <template #table-count="scope">
        {{ scope.row.count? Number(scope.row.count.toFixed(2)): scope.row.count }}
      </template>
      <template #table-handle-edit="scope">
        <el-button type="text" :icon="scope.row.status === 'save'? 'el-icon-edit': 'el-icon-view'" @click="gotoDetail(scope.row.billNo)">{{ scope.row.status === 'save'? '编辑': '查看' }}</el-button>
      </template>
      <template #table-handle-audit="scope">
        <el-button type="text" icon="el-icon-s-promotion" @click="doPromotion(scope.row)" :style="scope.row.status === 'save'? '': 'color: var(--el-color-warning)'">{{ scope.row.status === 'save'? '审核': '反审' }}</el-button>
      </template>
      <template #table-handle-delete="scope">
        <el-button v-if="scope.row.status === 'save'" type="text" icon="el-icon-delete" @click="doDelete(scope.row)" style="color: var(--el-color-danger)">删除</el-button>
        <span v-else></span>
      </template>
      <template #table-handle-download="scope">
        <el-button v-if="scope.row.status === 'audit'" type="text" icon="el-icon-download" @click="doDownload(scope.row)" style="color: var(--el-color-success);margin-left: 10px;">下载</el-button>
        <span v-else></span>
      </template>
      <template #footerBtn="data">
        已选行数:{{ selectionLength}},重量:{{selectCount}}
        <el-button type="primary" @click="doOpen" icon="el-icon-s-home" size="mini">选择行入库</el-button>
        <el-button type="primary" @click="doSelectDownload" icon="el-icon-s-home" size="mini">选择行下载</el-button>
      </template>
    </vb-page>
  </div>
  <upload-dialog ref="upload_dialog" upload-method="upload_prdcol_bill" @success="uploadFinish"></upload-dialog>
  <selectRowStockIn ref="selectRowStockIn" @success=""></selectRowStockIn>
</template>

<script>
import uploadDialog from '../components/uploadDialog.vue'
import selectRowStockIn from '../components/selectRowStockInDialog.vue'
import fi from "element-plus/packages/locale/lang/fi";
import el from "element-plus/packages/locale/lang/el";
import tr from "element-plus/packages/locale/lang/tr";

export default {
  data() {
    return {
      loading: false,
      materialLoading: false,
      reloadMaterial: false,
      selection: null,
      selectionLength:0,
      selectCount:0
    }
  },
  components: {
    uploadDialog,
    selectRowStockIn
  },
  methods: {
    //单据都是审核的情况下才允许导出
    isExport(){
      if(this.selectCount == 0){
        return true;
      }
      console.log(this.selection)
      let flag = this.selection.every((item,index) => {
        return item.status === 'audit'
      })
    console.log(flag)
      return !flag;
    },
    //判断是否都是同一个任务号
    isEqual(array){
      if (array.length > 0){
        return !array.some(function (value,index){
          return value !== array[0];
        });
      } else {
        return true;
      }
    },
    //判断所选物料是否是04开头
    isStart(materialList){
      // console.log(materialList)
      var isFlag = true;
      for (let i = 0; i <materialList.length ; i++) {
        var mat = materialList[i].startsWith('04')
        if (!mat){
          isFlag = false
          return isFlag;
        }
      }
      return isFlag;
    },
    //导出
    toExport(billNoList){
      if (!this.selection || this.selection === 0){
        this.$message.error('没有选择行')
        return
      }
      const arrBillNo = [];
      const taskBillNoList = [];
      //let taskBillNo = billNoList[0].taskBillNo;
      for (let i = 0;i<billNoList.length;i++){
        arrBillNo.push(billNoList[i].billNo)
        taskBillNoList.push(billNoList[i].taskBillNo)
      }
      if (this.selection.length > 1){
        //先判断物料是否都是产成品
        const materialList = billNoList.map(item=>item.materialNo);
        //判断这里的物料是否都是04开头的
        if (this.isStart(materialList)){
          // console.log(this.isStart(materialList))
          const newArr = billNoList.map(item=>item.taskBillNo);
          // const isRepeat = newArr.some((x,index,billNoList)=>billNoList.findIndex(y=>y==x) !=index);
          var isRepeat = this.isEqual(taskBillNoList)
            if (isRepeat){
              window.open(import.meta.env.VITE_EXPORT_URL + `prdColExport?billNoList=${ arrBillNo}`)
            } else {
              window.open(import.meta.env.VITE_EXPORT_URL + `prdColExportProduct?billNoList=${ arrBillNo}`)
            }

        } else if (!this.isStart(materialList)){
          var isRepeat = this.isEqual(taskBillNoList)
          if (isRepeat){
            window.open(import.meta.env.VITE_EXPORT_URL + `prdColExport?billNoList=${ arrBillNo}`)
          } else {
            this.$message.error('需要相同任务单号才可一起导出')
            return
          }
        }
      }
      if (this.selection.length == 1){
        window.open(import.meta.env.VITE_EXPORT_URL + `prdColExport?billNoList=${ arrBillNo}`)
      }

    },
    doSelect(data) {
      this.selection = data
      this.selectionLength = this.selection.length;
      this.selectCount=0
      for (var i=0;i<this.selectionLength;i++){
        this.selectCount+=data[i].count
      }
      this.selectCount = parseFloat(this.selectCount).toFixed(2)
     // console.log(this.selection)
     // console.log(data[0].billNo)
    },
    /**
     * 获取加载按钮的加载中状态
     */
    gotoDetail(billNo = '') {
      let url = '/produce/prdColDetail'
      if (billNo) {
        url += `?billNo=${ billNo }`
      }
      this.$router.push(url)
    },
    uploadFinish() {
      this.$message.success('上传完成!')
      this.$refs.page.reload()
    },
    async doSelectDownload() {
      if (!this.selection || this.selection.length === 0) {
        this.$message.error('没有选择行')
        return
      }
      let billNoList = []
      for(let i = 0; i < this.selection.length; i++) {
        if (this.selection[i].status === 'audit') {
          billNoList.push(this.selection[i].billNo)
        }
      }
      try {
        await this.$confirm(`确定下载单据吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('download_prdcol_bill_barcode_list', { billNoList: billNoList })
        if (!res.res) {
          return
        }
        this.$message.success(`批量下载完成!`)
      } finally {
        this.loading = false
      }
    },
    doOpen() {
      if (!this.selection || this.selection.length === 0) {
        this.$message.error('没有选择行')
        return
      }
      this.$refs.selectRowStockIn.open(this.doPrdIn)
    },
    async doPrdIn(form) {
      let billNoList = []
      for(let i = 0; i < this.selection.length; i++) {
        if (this.selection[i].status === 'audit') {
          billNoList.push(this.selection[i].billNo)
        }
      }
      try {
        await this.$confirm(`已审核单据(${ billNoList.length }件)将被执行采购入库, 本次操作不校验箱号是否已经绑定RFID, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('save_user_prdin_by_prdcol_list', {
          billNoList: billNoList,
          stockNo: form.stockNo,
          locationNo: form.locationNo
        })
        if (!res.res) {
          return
        }
        this.$message.success(`入库完成!`)
        return true;
      } finally {
        this.loading = false
      }
    },
    async doPromotion(row) {
      this.loading = true
      try {
        if (row.status === 'save') {
          let res = await this.callApi('audit_prdcol_bill', { billNo: row.billNo })
          if (!res.res) {
            return
          }
          this.$message.success(`单据【${ row.billNo }】审核完成`)
          row.status = 'audit'
        } else {
          let res = await this.callApi('unaudit_prdcol_bill', { billNo: row.billNo })
          if (!res.res) {
            return
          }
          this.$message.success(`单据【${ row.billNo }】反审完成`)
          row.status = 'save'
        }
      } finally {
        this.loading = false
      }
    },
    async doDelete(row) {
      try {
        await this.$confirm(`确定删除单据【${ row.billNo }】吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('delete_prdcol_bill', { billNo: row.billNo })
        if (!res.res) {
          return
        }
        this.$message.success(`已删除`)
        this.$refs.page.reload()
      } finally {
        this.loading = false
      }
    },
    async doDownload(row) {
      try {
        await this.$confirm(`确定下载单据【${ row.billNo }】吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('download_prdcol_bill_barcode', { billNo: row.billNo })
        if (!res.res) {
          return
        }
        this.$message.success(`已下载`)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>

</style>
